package br.os.communication;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import br.os.model.Usuario;

/**
 * CommAutenticacao
 * Classe responsavel por enviar uma solicitação de autenticão ao servidor
 */
public class CommAutenticar extends Thread {
	private CommNotificador notificador;
	private String url;
	private Usuario user;

	/**
	 * @param url
	 * @param usuario
	 * @param notificador
	 */
	public CommAutenticar(String url, Usuario user,CommNotificador notificador) {
		this.url = url;
		this.user = user;
		this.notificador = notificador;
	}

	/**
	 * Envia uma requisicao de autenticacao ao Servidor.
	 */
	public void run() {
		try {
			HttpConnection httpConnection = (HttpConnection) Connector.open(url);
			httpConnection.setRequestMethod(HttpConnection.POST);
			httpConnection.setRequestProperty("User-Agent","Profile/MIDP-2.1 Configuration/CLDC-1.1");
			httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			String encoded = "login=" + user.getLogin() + "&senha=" + user.getSenha();
			httpConnection.setRequestProperty("Content-Length", Integer.toString(encoded.length()));
			httpConnection.openOutputStream().write(encoded.getBytes());
			notificador.notificarInputStream(httpConnection.openInputStream());
		} catch (Exception e) {
			notificador.notificarException(e);
		}
	}

}
